/**
 * Created by Freeman on 2018/1/20.
 */
import {combineReducers} from 'redux';

import * as entities from './';
import {ADD_ENTITIES} from "../../constants/ActionTypes";
import topicsReducer from './topics/reducer'
import channelsReducer from './channels/reducer'

const entityReducers = {
  topics: topicsReducer,
  channels: channelsReducer,
};

/**
 * Generates a reducer which will handle all entity requests.
 * @param  {Entity} entity    Entity which should be handled
 * @return {state}            New state
 */
const createEntityReducer = (key: string) => (state = {}, action) => {
  const entityReducer = entityReducers[key];
  // If there is no reducer we should use a placeholder
  const reducer = entityReducer || ((_state = {} || {}) => _state);

  let newState = state;
  if (action.type === ADD_ENTITIES) {
    const data = action.entities[key];

    if (!data) return reducer(state, action);
    newState = { ...state, ...data };
  }

  return reducer(newState, action);
};
const reducers = Object.keys(entities.default).reduce((total, next) => {
  const entity = entities.default[next];
  return {
    ...total,
    [next]: createEntityReducer(next, entity),
  };
}, {});
export default combineReducers(reducers);
